package cn.edu.sasu.adapter.newsdetail.photo;

import java.io.File;
import java.util.List;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import cn.edu.sasu.R;
import cn.edu.sasu.domain.News;
import cn.edu.sasu.http.HttpRequestService;

public class PhotoAdapter extends BaseAdapter {
	private List<News> list;
	private Context context;

	public PhotoAdapter(List<News> list, Context context) {
		this.context = context;
		this.list = list;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		PhotoView pv;
		if (convertView == null) {
			pv = new PhotoView();

			convertView = ((LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
					.inflate(R.layout.picture_item, null);

			pv.photo = (ImageView) convertView.findViewById(R.id.photo);
			pv.title = (TextView) convertView.findViewById(R.id.title);
			pv.comments_count = (TextView) convertView
					.findViewById(R.id.comments_count);
			convertView.setTag(pv);
		} else {
			pv = (PhotoView) convertView.getTag();
		}
		News news = list.get(position);
		pv.title.setText(news.getNewsTitle());

		pv.comments_count.setText(news.getCommentsCount()
				+ context.getResources().getString(R.string.comment));

		if (news.getPhotos() != null) {
			String photoName = news.getPhotos().get(0).getNewsResourceUrl();
			String photoUrl = context.getResources().getString(
					R.string.sasufile);
			File file = new File(photoUrl, photoName.split("/")[1]);
			// 从后台读取照片
			if (!file.exists()) {
				new HttpRequestService().putPhoto(photoName, context);
			}
			pv.photo.setImageURI(Uri.fromFile(file));
		} else {
			pv.photo.setImageResource(R.drawable.item_icon);
		}

		return convertView;
	}

	public static class PhotoView {
		TextView title;
		ImageView photo;
		TextView comments_count;
	}

}
